package com.googlecode.restitory.gae.hook;

import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.googlecode.mycontainer.commons.file.PathUtil;
import com.googlecode.restitory.gae.GAERequestUtil;
import com.googlecode.restitory.gae.Request;
import com.googlecode.restitory.gae.RequestJsoner;
import com.googlecode.restitory.gae.Response;

public class QueueHook implements Hook {

	@Override
	public Response execute(Request request, Chain chain) {
		String path = request.getPath();
		if (path.startsWith("/_/queue")) {
			Request nreq = request.copy().setPath(path.substring(8));
			return queue(nreq).copy().setRequest(request);
		}
		return chain.execute(request);
	}

	public DatastoreService getDatastoreService() {
		return DatastoreServiceFactory.getDatastoreService();
	}

	private Response queue(Request req) {
		String path = req.getPath();
		List<String> split = PathUtil.split(path);
		String queueName = split.get(0);
		String json = req.getContent().toString();
		List<Request> requests = RequestJsoner.parseRequestListJson(json);
		Queue queue = QueueFactory.getQueue(queueName);
		List<TaskOptions> tasks = GAERequestUtil.requestToTask(requests);
		queue.add(tasks);
		return new Response(req).setCode(200);
	}
}
